package uk.ac.imperial.gpaexpress.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Connection;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class Solve extends HttpServlet {
	Connection conn;

	Socket requestSocket;
	PrintWriter out;
	BufferedReader in;
	String source;

	String user;
	String model_title;
	String params_title;
	
	String host = "localhost";
	int port = 4444;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		// Get request
		try{
			resp.setContentType("text/html");

			//get session and model details for processing
			HttpSession session = req.getSession(true);
			user = (String) session.getAttribute("email");
			model_title = req.getHeader("model");
			params_title = req.getHeader("params");

		} catch (Exception e) {
			e.printStackTrace();
		}

		// Send model to Server process for solving
		try{
			// Set up connection
			requestSocket = new Socket(host, port);
			out = new PrintWriter(requestSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
			System.out.println("client> Connection established");

			// Communicate with server: email, model_title, params_title
			out.println(user);
			out.println(model_title);
			out.println(params_title);
			System.out.println("client> Model details sent");

			String serverResponse;
			while ((serverResponse = in.readLine()) != null) {
				System.out.println("SolveServlet> Server says \"" + serverResponse + "\"");
			}
			System.out.println("SolveServlet> End of communication with server");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// Close connection with server
			try{
				in.close();
				out.close();
				requestSocket.close();
				System.out.println("client> Connection closed");
			}
			catch(IOException e){
				e.printStackTrace();
			}
		}
	}
}
